import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  MenuItem,
  Button,
  Typography,
  Pagination,
  Chip,
  CircularProgress,
  Paper,
  InputAdornment,
  Divider,
} from '@mui/material';
import { Search, School, Work, Category, LocationOn, Grade, EmojiEvents } from '@mui/icons-material';
import { graduateAPI } from '../../services/api';

const ExperienceSearch = () => {
  const [loading, setLoading] = useState(false);
  const [experiences, setExperiences] = useState([]);
  const [totalPages, setTotalPages] = useState(0);
  const [filters, setFilters] = useState({
    major: '',
    careerPath: '',
    experienceType: '',
    keyword: '',
    page: 0,
    size: 10
  });

  const careerPaths = ['就业', '考研', '出国'];
  const experienceTypes = ['就业经验', '考研经验', '留学经验', '实习经验'];
  const majors = ['计算机科学', '软件工程', '信息管理', '数据科学'];

  useEffect(() => {
    searchExperiences();
  }, [filters.page]);

  const searchExperiences = async () => {
    try {
      setLoading(true);
      const params = {
        ...filters,
        major: filters.major || null,
        careerPath: filters.careerPath || null,
        experienceType: filters.experienceType || null,
        keyword: filters.keyword || null,
      };
      
      Object.keys(params).forEach(key => {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      });

      const response = await graduateAPI.searchExperiences(params);
      if (response.data.content) {
        setExperiences(response.data.content);
        setTotalPages(response.data.totalPages);
      } else {
        setExperiences([]);
        setTotalPages(0);
      }
    } catch (error) {
      console.error('搜索失败:', error);
      setExperiences([]);
      setTotalPages(0);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setFilters(prev => ({ ...prev, page: 0 }));
    searchExperiences();
  };

  const handlePageChange = (event, newPage) => {
    setFilters(prev => ({ ...prev, page: newPage - 1 }));
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        经验信息检索
      </Typography>

      {/* 搜索过滤器 */}
      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={12} md={3}>
            <TextField
              fullWidth
              select
              label="专业"
              value={filters.major}
              onChange={(e) => setFilters(prev => ({ ...prev, major: e.target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <School />
                  </InputAdornment>
                ),
              }}
            >
              <MenuItem value="">全部专业</MenuItem>
              {majors.map((major) => (
                <MenuItem key={major} value={major}>
                  {major}
                </MenuItem>
              ))}
            </TextField>
          </Grid>
          <Grid item xs={12} md={3}>
            <TextField
              fullWidth
              select
              label="发展方向"
              value={filters.careerPath}
              onChange={(e) => setFilters(prev => ({ ...prev, careerPath: e.target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Work />
                  </InputAdornment>
                ),
              }}
            >
              <MenuItem value="">全部方向</MenuItem>
              {careerPaths.map((path) => (
                <MenuItem key={path} value={path}>
                  {path}
                </MenuItem>
              ))}
            </TextField>
          </Grid>
          <Grid item xs={12} md={3}>
            <TextField
              fullWidth
              select
              label="经验类型"
              value={filters.experienceType}
              onChange={(e) => setFilters(prev => ({ ...prev, experienceType: e.target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Category />
                  </InputAdornment>
                ),
              }}
            >
              <MenuItem value="">全部类型</MenuItem>
              {experienceTypes.map((type) => (
                <MenuItem key={type} value={type}>
                  {type}
                </MenuItem>
              ))}
            </TextField>
          </Grid>
          <Grid item xs={12} md={3}>
            <TextField
              fullWidth
              label="关键词搜索"
              value={filters.keyword}
              onChange={(e) => setFilters(prev => ({ ...prev, keyword: e.target.value }))}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Search />
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          <Grid item xs={12}>
            <Button
              variant="contained"
              onClick={handleSearch}
              startIcon={<Search />}
              sx={{
                background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
                color: 'white',
              }}
            >
              搜索
            </Button>
          </Grid>
        </Grid>
      </Paper>

      {/* 搜索结果列表 */}
      {loading ? (
        <Box display="flex" justifyContent="center" p={3}>
          <CircularProgress />
        </Box>
      ) : (
        <Grid container spacing={3}>
          {experiences.map((experience) => (
            <Grid item xs={12} key={experience.id}>
              <Card 
                sx={{ 
                  transition: 'transform 0.2s',
                  '&:hover': {
                    transform: 'translateY(-4px)',
                    boxShadow: 4,
                  }
                }}
              >
                <CardContent>
                  <Grid container spacing={2}>
                    <Grid item xs={12} md={8}>
                      <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                        <Typography variant="h6" component="div">
                          {experience.name} - {experience.major}
                        </Typography>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                        <Work sx={{ mr: 1, color: 'primary.main' }} />
                        <Typography color="textSecondary">
                          {experience.workplace} | {experience.position}
                        </Typography>
                      </Box>
                      <Box sx={{ mb: 2 }}>
                        <Chip 
                          label={experience.careerPath}
                          color="primary"
                          size="small"
                          sx={{ mr: 1 }}
                        />
                        <Chip 
                          label={experience.experienceType}
                          color="secondary"
                          size="small"
                          sx={{ mr: 1 }}
                        />
                        <Chip 
                          label={`GPA: ${experience.gpa}`}
                          variant="outlined"
                          size="small"
                        />
                      </Box>
                      <Typography variant="body2" paragraph>
                        {experience.experience}
                      </Typography>
                    </Grid>
                    <Grid item xs={12} md={4}>
                      <Box sx={{ mb: 2 }}>
                        <Typography variant="subtitle2" gutterBottom>
                          技能标签：
                        </Typography>
                        <Box>
                          {experience.skills?.split(',').map((skill, index) => (
                            <Chip
                              key={index}
                              label={skill.trim()}
                              size="small"
                              sx={{ m: 0.5 }}
                            />
                          ))}
                        </Box>
                      </Box>
                      <Divider sx={{ my: 2 }} />
                      <Box>
                        <Typography variant="subtitle2" gutterBottom>
                          获奖情况：
                        </Typography>
                        <Typography variant="body2" color="textSecondary">
                          {experience.awards}
                        </Typography>
                      </Box>
                    </Grid>
                  </Grid>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      {/* 分页 */}
      {totalPages > 0 && (
        <Box sx={{ mt: 3, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            count={totalPages}
            page={filters.page + 1}
            onChange={handlePageChange}
            color="primary"
          />
        </Box>
      )}
    </Box>
  );
};

export default ExperienceSearch; 